package config

import (
	"company_website/src/global"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
	"os"
	"path"
)

func InitViper() {
	rootDir, _ := os.Getwd()
	fmt.Println("dev路径：")
	fmt.Println(rootDir)
	fmt.Println()
	configPath := path.Join(rootDir, "config", "yaml")

	v := viper.New()
	v.AddConfigPath(configPath)
	v.SetConfigName(global.ENVIRONMENT_MAP[global.ENVIRONMENT])
	v.SetConfigType("yaml")

	//读取文件
	err := v.ReadInConfig()
	if err != nil {
		panic(any(fmt.Errorf("Fatal error config file: %s \n", err)))
	}

	//配置文件监听
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		if err := v.Unmarshal(&global.GVL_CFG); err != nil {
			fmt.Println(err)
		}
	})
	if err := v.Unmarshal(&global.GVL_CFG); err != nil {
		fmt.Println(err)
	}
}
